<template>
	<up-popup :show="popupShow" :round="8" mode="bottom" @close="close">
		<view class="popup-box">
			<view class="comment-box" v-if="firstLevelComments.length > 0">
				<view class="comment-item" v-for="(item, index) in firstLevelComments" :key="item">
					<view class="left-user-head-box">
						<image class="user-head-src" :src="item.headSrc" />
					</view>
					<view class="right-info-box">
						<userInfoVue :userInfo="item" :index="index" @replyCB="onReply" @delCB="onDel" :flag="null"
							@linkCB="onLink" />
						<view class="divider-box" v-if="item.totalRecover > 0 && curcommentIndex != index">
							<up-divider :text="'展开'+ item.totalRecover + '条回复'"
								@click="handleComment(index, item)"></up-divider>
						</view>

						<!-- 二级 。 子级 -->
						<view v-if="commentFlag && curcommentIndex == index">
							<block v-for="(itemChild, chindIndex) in commentReply">
								<view style="width: 100%; display: flex; margin-top: 24rpx;">
									<view class="chlid-left-user-head-box">
										<image class="user-head-src" :src="itemChild.headSrc" />
									</view>
									<view class="chlid-right-info-box">
										<userInfoVue :userInfo="itemChild" :index="chindIndex" @replyCB="onReply"
											@delCB="onDel" @linkCB="onLink" :flag="'childLevel'" />
									</view>
								</view>
							</block>
						</view>

						<view class="viewing-and-storing" v-if="commentFlag && curcommentIndex == index">
							<text v-if="commentReplyViewMoreCommentsFlag" @click="handleView(item)">查看更多</text>
							<text style="margin-left: 40rpx;" @click="handleRetract(index)">收起</text>
						</view>
					</view>
				</view>

				<view class="see-more" v-if="viewMoreCommentsFlag" @click="handleCommentFunc">查看更多评论</view>
			</view>

			<!-- 输入框 -->
			<view class="input-box">
				<up-input :placeholder="placeholderText" v-model="content" border="surround"
					style="border-radius: 12rpx;" clearable @blur="onBlur" @input="onInput"></up-input>
				<view class="u-button">
					<up-button type="primary" text="发送" @click="onSend"></up-button>
				</view>
			</view>
		</view>
	</up-popup>
</template>

<script setup lang="ts">
	import { defineProps, ref } from 'vue';
	import userInfoVue from './userInfo.vue';
	import { getFindPageListApi, commentsSaveApi, commentsDelByIdApi, commentsCurrencyCountApi, recoverSaveApi, recoverFindPageListApi, recoverDelByIdApi, recoverCurrencyCountApi } from '@/api/funCircleApi.js';
	import { isUniqueArray, isEmptyObject } from '@/utils/common.js'

	const props = defineProps({
		popupShow: Boolean,
		currentUserId: Number
	});

	// 引入组件
	components: {
		userInfoVue
	};
	// 外层tag下动态id
	const trendsId = ref(null)

	// 一级评论数据
	const commentTotalPages = ref(0)
	const commentCurrentPage = ref(1);
	const pageSize = 10;
	const firstLevelComments = ref([])

	// 二级回复数据
	const commentReplyTotalPages = ref(0)
	const commentReplyCurrentPage = ref(1);
	const commentReply = ref([])

	// 展开状态
	const commentFlag = ref(false)
	const curcommentIndex = ref(null)

	// 输入框提示文案
	const placeholderText = ref('有爱评论,说点好听的~')
	// 输入框内容
	const content = ref('')
	// 评论id
	const commentId = ref(null)
	// 当前评论的信息
	const curCommentInfo : any = ref({})
	// 当前评论的回复的信息
	const curChildCommentInfo : any = ref({})
	// 当前回复的层级
	const replyHierarchyFlag = ref(null)

	// 查看更多
	const commentReplyViewMoreCommentsFlag = ref(false)
	// 查看更多评论
	const viewMoreCommentsFlag = ref(false)

	// 定义事件
	const emit = defineEmits(['closeCB'])

	const getCommentData = async (id) => {
		// id -> tag下面的某条动态id
		if(id != trendsId.value) firstLevelComments.value = []
		trendsId.value = id
		await commentDataList(id)
	}

	// 获取分页评论的数据
	const commentDataList = async (id) => {
		let { code, errorMsg, results: { records, total } } = await getFindPageListApi({
			graphicId: id,
			currentPage: commentCurrentPage.value,
			pageSize: pageSize,
			currentUserId: props.currentUserId,
		})
		if (code == 200) {
			firstLevelComments.value = isUniqueArray(firstLevelComments.value, records)
			commentTotalPages.value = Math.ceil(total / pageSize)
			if (commentTotalPages.value > commentCurrentPage.value) {
				viewMoreCommentsFlag.value = true
			} else {
				viewMoreCommentsFlag.value = false
			}
		} else {
			console.log(errorMsg)
		}
	}


	// 关闭弹窗事件
	const close = () => {
		commentFlag.value = false
		curcommentIndex.value = null
		content.value = ''
		placeholderText.value = '有爱评论,说点好听的~'
		emit('closeCB')
	}

	// 点击查看更多评论 - 事件
	const handleCommentFunc = async () => {
		commentCurrentPage.value = ++commentCurrentPage.value
		await commentDataList(trendsId.value)
	}

	// 点击展开查看更多
	const handleComment = async (index, item) => {
		commentFlag.value = true
		curcommentIndex.value = index
		// 获取回复评论的分页数据
		commentReply.value = []
		commentId.value = item.id
		await recoverFindPageList(item)
	}

	// 点击回复评论查看更多
	const handleView = async (item) => {
		commentReplyCurrentPage.value = ++commentReplyCurrentPage.value
		await recoverFindPageList(item)
	}

	// 回复评论分页数据
	const recoverFindPageList = async (item) => {
		let { code, errorMsg, results } = await recoverFindPageListApi({
			currentUserId: props.currentUserId,
			graphicCommentsId: item.id || commentId.value,
			graphicId: item.graphicId || trendsId.value,
			pageSize,
			currentPage: commentReplyCurrentPage.value
		})
		if (code == 200) {
			commentReply.value = isUniqueArray(commentReply.value, results.records)
			commentReplyTotalPages.value = Math.ceil(results.total / pageSize)
			if (commentReplyTotalPages.value > commentReplyCurrentPage.value) {
				commentReplyViewMoreCommentsFlag.value = true
			} else {
				commentReplyViewMoreCommentsFlag.value = false
			}
		} else {
			errTips()
		}
	}

	// 点击收起
	const handleRetract = (index) => {
		commentFlag.value = false
		curcommentIndex.value = null
	}

	// 子组件回复的事件回调
	const onReply = (item : any, flag : any) => {
		if (flag == 'childLevel') {
			curChildCommentInfo.value = item
		} else {
			curCommentInfo.value = item
		}
		content.value = null
		replyHierarchyFlag.value = flag
		placeholderText.value = `回复 @${item.userName}`
	}

	// 输入框输入事件
	const onInput = (newValue) => {
		content.value = newValue.trim();
	}

	// 输入框失去焦点事件
	const onBlur = () => {
		if (!content.value.length) {
			placeholderText.value = '有爱评论,说点好听的~'
		}
	}

	// 发送
	const onSend = async () => {
		if (!content.value || content.value.length == 0) {
			uni.showToast({ title: '请输入内容', icon: 'error' });
		} else {
			// 一级评论新增
			if (isEmptyObject(curCommentInfo.value)) {
				if (replyHierarchyFlag.value != 'childLevel') {
					// 一级直接评论
					await commentsSave()
				} else {
					await firstLevelReplyAdd()
				}
			} else {
				if (replyHierarchyFlag.value != 'childLevel') {
					// 一级评论回复
					await firstLevelReplyAdd()
				} else {
					// 一级评论回复的回复
					await firstLevelReplyAdd()
				}
			}
		}
	}

	// 一级评论新增
	const commentsSave = async () => {
		let { code, errorMsg } = await commentsSaveApi({
			content: content.value,
			graphicId: trendsId.value,
			currentUserId: props.currentUserId
		})
		if (code == 200) {
			uni.showToast({ title: '已回复', icon: 'success' });
			emptyContentFunc()
			await commentDataList(trendsId.value)
		} else {
			uni.showToast({ title: `${errorMsg}`, icon: 'error' });
		}
	}

	// 一级评论回复新增
	const firstLevelReplyAdd = async () => {
		let { code, errorMsg } = await recoverSaveApi({
			content: content.value,
			graphicId: trendsId.value,
			graphicCommentsId: curCommentInfo.value?.id || commentId.value,
			currentUserId: props.currentUserId,
			parentId: replyHierarchyFlag.value != 'childLevel' ? null : curChildCommentInfo.value.id
		})
		if (code == 200) {
			uni.showToast({ title: '已回复', icon: 'success' });
			emptyContentFunc()
			await commentDataList(trendsId.value)
			// 当回复里面展开再次获取列表数据
			if (commentFlag.value) {
				await recoverFindPageList(curCommentInfo.value)
			}
		} else {
			uni.showToast({ title: `${errorMsg}`, icon: 'error' });
		}
	}

	// 评论删除
	const onDel = async (item, flag) => {
		if (flag == 'childLevel') {
			let { code, errorMsg } = await recoverDelByIdApi({
				id: item.id
			})
			if (code == 200) {
				uni.showToast({ title: '已删除', icon: 'success' });
				let newCommentReply = commentReply.value.filter(curItem => curItem.id != item.id)
				commentFlag.value = newCommentReply.length == 0 ? false : true
				commentReply.value = newCommentReply
				await commentDataList(trendsId.value)
			} else {
				uni.showToast({ title: `${errorMsg}`, icon: 'error' });
			}
		} else {
			let { code, errorMsg } = await commentsDelByIdApi({
				id: item.id
			})
			if (code == 200) {
				uni.showToast({ title: '已删除', icon: 'success' });
				let newFirstLevelComments = firstLevelComments.value.filter(curItem => curItem.id != item.id)
				firstLevelComments.value = newFirstLevelComments
			} else {
				uni.showToast({ title: `${errorMsg}`, icon: 'error' });
			}
		}
	}

	// 点赞
	const onLink = async (item, index, flag : any) => {
		if (flag == 'childLevel') {
			let { code, errorMsg } = await recoverCurrencyCountApi({
				flag: !item.likeStatus,
				graphicCommentsId: item.id,
				type: 1,
				currentUserId: props.currentUserId
			})
			if (code == 200) {
				commentReply.value[index].likeStatus = !item.likeStatus
				if (!item.likeStatus) {
					commentReply.value[index].totalLikes = --item.totalLikes
				} else {
					commentReply.value[index].totalLikes = ++item.totalLikes
				}
			} else {
				uni.showToast({ title: `${errorMsg}`, icon: 'error' });
			}
		} else {
			let { code, errorMsg } = await commentsCurrencyCountApi({
				flag: !item.likeStatus,
				graphicCommentsId: item.id,
				type: 1,
				currentUserId: props.currentUserId
			})
			if (code == 200) {
				firstLevelComments.value[index].likeStatus = !item.likeStatus
				if (!item.likeStatus) {
					firstLevelComments.value[index].totalLikes = --item.totalLikes
				} else {
					firstLevelComments.value[index].totalLikes = ++item.totalLikes
				}
			} else {
				uni.showToast({ title: `${errorMsg}`, icon: 'error' });
			}
		}
	}

	// 清空内容
	const emptyContentFunc = () => {
		content.value = null
		placeholderText.value = '有爱评论,说点好听的~'
	};

	// 成功提示
	const successTips = () => {
		uni.showToast({ title: '操作成功', icon: 'success' });
	}

	// 异常提示
	const errTips = () => {
		uni.showToast({ title: '操作异常', icon: 'error' });
	}

	defineExpose({
		emptyContentFunc,
		getCommentData
	});
</script>

<style lang="scss" scoped>
	.popup-box {
		max-height: 800rpx;
		width: 100%;
		overflow: auto;
		box-sizing: border-box;
		display: flex;
		flex-direction: column;
		justify-content: space-between;

		.comment-box {
			width: 100%;
			height: calc(100% - 100rpx);
			padding: 24rpx 24rpx 0 24rpx;
			box-sizing: border-box;
			overflow: auto;

			.comment-item {
				width: 100%;
				background-color: #fff;
				display: flex;
				padding-bottom: 12rpx;
				box-sizing: border-box;
				border-bottom: 1rpx solid #f5f5f5;
				margin-bottom: 24rpx;

				.left-user-head-box {
					width: 88rpx;
					margin-right: 24rpx;

					.user-head-src {
						width: 88rpx;
						height: 88rpx;
						border-radius: 50%;
					}
				}

				.right-info-box {
					width: calc(100% - 88rpx - 24rpx);


					.viewing-and-storing {
						width: 100%;
						margin-top: 24rpx;
						font-size: 28rpx;
						color: #ccc;
					}

					.chlid-left-user-head-box {
						width: 88rpx;
						margin-right: 24rpx;

						.user-head-src {
							width: 88rpx;
							height: 88rpx;
							border-radius: 50%;
						}
					}

					.chlid-right-info-box {
						width: calc(100% - 88rpx - 24rpx);
					}
				}
			}

			.comment-item:last-child {
				border-bottom: 0rpx solid #fff !important;
			}

			.see-more {
				width: 100%;
				color: #000;
				display: flex;
				justify-content: center;
				margin-bottom: 24rpx;
			}
		}

		.input-box {
			padding: 0 24rpx;
			box-sizing: border-box;
			height: 88rpx;
			display: flex;
			align-items: center;
			justify-content: space-between;
			box-shadow: 0 -5px 5px -2px rgba(0, 0, 0, 0.4);

			.u-button {
				width: 120rpx;
				margin-left: 24rpx;
			}
		}
	}
</style>